﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JasLib.Extensions;

namespace JasLib.Interop.Win32
{
    public class COMException : System.Runtime.InteropServices.COMException
    {
        public COMException(string message, Exception inner)
            : base(message, inner)
        {
        }

        public COMException(string message, HRESULT errorCode)
            : base(message, (int)errorCode)
        {
        }

        public HRESULT HRESULT
        {
            get
            {
                return (HRESULT)(uint)base.ErrorCode;
            }
        }

        public override string Message
        {
            get
            {
                return string.Format("{0} (0x{1:8x}) : {2}", (HRESULT)(uint)base.ErrorCode, base.ErrorCode, base.Message);
            }
        }
    }

    public class EsentException : Exception
    {
        private JET_ERR _error;
        public JET_ERR ErrorCode
        {
            get { return _error; }
        }

        public EsentException(JET_ERR error, string strCallerMessage = null)
            : base(RenderMessage(error, strCallerMessage))
        {
            _error = error;
        }

        protected static string RenderMessage(JET_ERR error, string strCallerMessage)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0} ({1}) : ", error, (int)error);

            strCallerMessage = strCallerMessage.TrimToNull();
            string strErrorString = error.ToErrorString().TrimToNull();

            if (strCallerMessage != null && strErrorString != null)
                sb.AppendFormat("{0} ({1})", strCallerMessage, strErrorString);
            else if (strCallerMessage != null)
                sb.Append(strCallerMessage);
            else if (strErrorString != null)
                sb.Append(strErrorString);

            return sb.ToString();
        }
    }

    public class Win32Exception : System.ComponentModel.Win32Exception
    {
        public Win32Exception()
        {
        }

        public Win32Exception(Win32ErrorCode error, string message = null)
            : base((int)error, message)
        {
        }

        public Win32Exception(string message)
            : base(message)
        {
        }

        public Win32Exception(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        public Win32ErrorCode Win32ErrorCode
        {
            get
            {
                return (Win32ErrorCode)base.NativeErrorCode;
            }
        }

        public override string Message
        {
            get
            {
                return string.Format("{0} ({1}) : {2}", (Win32ErrorCode)base.NativeErrorCode, base.NativeErrorCode, base.Message);
            }
        }
    }
}
